﻿#region Using directives
using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProcolDemo.I18N;
using ProcolDemo.Ratings;
using ProcolDemo.User;

#endregion

namespace ProcolDemo {
    public partial class ProfViewProfile : Page {
        private readonly I18NService I18N = new I18NService();

        protected void Page_Load(object sender, EventArgs e) {
            if (!Common.IsUserLoggedIn(Session))
                Response.Redirect("Default.aspx");

            var userService = new UserService();

            Common.FillI18NStrings(this, Session);

            int uidSession = Common.GetUserId(Session);
            int uidRequest = Common.GetUserId(Request);

            if (uidRequest < 0) {
                var MP = (MasterPage) Master;
                MP.PopupError.Show();
            } else {
                lblProfProfileInfo.Text = String.Format(I18N.GetTextAccordingToUserId(uidSession, "PROFILE_INFO"),
                                                        userService.GetUserUsername(uidRequest));

                #region Update info
                if (IsPostBack) {
                    if (!String.IsNullOrEmpty(getActualMajorId(txtProfMajors.Text)))
                        userService.SetUserMajor(uidSession, getActualMajorId(txtProfMajors.Text));

                    if (!String.IsNullOrEmpty(txtProfNewDOB.Text)) {
                        DateTime dt = DateTime.Parse(txtProfNewDOB.Text);
                        userService.SetUserDOB(uidSession, dt);
                        txtProfNewDOB_CalendarExtender.SelectedDate = dt;

                        txtProfNewDOB.Visible = false;
                    }
                }
                #endregion

                #region Get/set user rating
                var ratingService = new RatingService();

                try {
                    var rating = ratingService.GetUserRating(uidRequest);

                    ProfRating.CurrentRating = rating;
                } catch (InvalidOperationException) {
                    ProfRating.CurrentRating = 0;
                }
                #endregion

                #region Get user info
                bool ownProfile = (uidRequest == uidSession);
                DateTime dob = userService.GetUserDOB(uidRequest);

                txtProfMajors.BorderStyle = ownProfile ? BorderStyle.Dashed : BorderStyle.None;
                txtProfMajors.ReadOnly = !ownProfile;

                if (!ownProfile)
                    txtProfMajors.CssClass = "nobackground";
                else
                    imgProfCalendar.Visible = true;

                txtProfMajors.Text = userService.GetUserMajor(uidRequest, Common.GetUserLanguage(uidSession));
                imgProfGender.Src = Common.GetUserGender(uidRequest) == Common.Gender.Male
                                            ? "/images/male.png"
                                            : "/images/female.png";
                lblProfEmail.Text = userService.GetUserMail(uidRequest);
                ProfprofileEmail.HRef = String.Format("mailto:{0}", lblProfEmail.Text);
                lblProfName.Text = userService.GetUserName(uidRequest);
                lblProfAge.Text = String.Format(I18N.GetTextAccordingToUserId(uidSession, "PROFILE_AGESTR"), GetAge(dob),
                                                dob.ToShortDateString());
                lblProfAge.ToolTip = GetAge(dob, uidSession);
                #endregion

                #region Projects
                IntString[] projects = userService.GetProjects(uidRequest);

                dataProfProjects.DataSource = projects;
                dataProfProjects.DataBind();
                #endregion

                #region Ideas
                // TODO: Change
                lblProfNumIdeas.Text = String.Format(I18N.GetTextAccordingToUserId(uidRequest, "PROF_PROFILE_IDEANUM"), 1);
                #endregion

                const string strKey = "calendarExtenderPostback";
                if (!ClientScript.IsClientScriptBlockRegistered(GetType(), strKey)) {
                    String strScript = String.Format("function calendarExtenderPostback(e) {{ {0} }}",
                                                     ClientScript.GetPostBackEventReference(btnProfCalendar,
                                                                                            String.Empty));
                    ClientScript.RegisterClientScriptBlock(GetType(), strKey, strScript, true);
                }
            }

            txtProfMajors_AutoCompleteExtender.CompletionSetCount = Common.GetUserLanguage(uidRequest);
        }

        private static int GetAge(DateTime date) {
            int years = DateTime.Now.Year - date.Year;

            date = date.AddYears(years);

            if (DateTime.Now.CompareTo(date) < 0)
                years--;

            return years;
        }

        private String GetAge(DateTime date, int uid) {
            int years = DateTime.Now.Year - date.Year;
            int months;

            if (DateTime.Now < date.AddYears(years) && years != 0)
                --years;

            date = date.AddYears(years);
            if (date.Year == DateTime.Now.Year)
                months = DateTime.Now.Month - date.Month;
            else
                months = (12 - date.Month) + DateTime.Now.Month;

            if (DateTime.Now < date.AddMonths(months) && months != 0)
                --months;

            date = date.AddMonths(months);
            int days = (DateTime.Now - date).Days;

            return String.Format(I18N.GetTextAccordingToUserId(uid, "PROFILE_DOBSTR"), years, months, days);
        }

        protected void txtProfMajors_TextChanged(object sender, EventArgs e) {
        }

        private static String getActualMajorId(String str) {
            var re = new Regex(@"^(?<major>\w{3,})(?: -)?");
            Match m = re.Match(str);

            if (m.Success)
                return m.Groups["major"].ToString();

            return String.Empty;
        }

        protected void btnCalendar_Click(object sender, EventArgs e) {
            var userService = new UserService();
            int uidSession = Common.GetUserId(Session);

            DateTime dt = DateTime.Parse(txtProfNewDOB.Text);
            userService.SetUserDOB(uidSession, dt);
        }

        protected void imgCalendar_Click(object sender, ImageClickEventArgs e) {
            var userService = new UserService();
            int uidSession = Common.GetUserId(Session);

            txtProfNewDOB_CalendarExtender.SelectedDate = userService.GetUserDOB(uidSession);
            txtProfNewDOB.Visible = true;
            txtProfNewDOB_CalendarExtender.Animated = true;
        }
    }
}